import { DataSet } from 'choerodon-ui/pro';
import intl from 'utils/intl';
import { BASE_SERVER, API_HOST } from '@src/utils/constants';
import { getCurrentOrganizationId, getCurrentUserId } from 'utils/utils';
import { FieldIgnore, FieldType, DataSetSelection } from 'choerodon-ui/pro/lib/data-set/enum';
import { AxiosRequestConfig } from 'axios';
import request from 'utils/request';
import notification from 'utils/notification';

const modelPrompt = 'tarzan.purchase.supplierAllocation';

const tenantId = getCurrentOrganizationId();

const userId = getCurrentUserId();



const listPageFactory = () =>
  new DataSet({
    selection: DataSetSelection.multiple,
    primaryKey: 'supplierAttrId',
    pageSize: 10,
    autoQuery: false,
    dataKey: 'content',
    totalKey: 'totalElements',
    queryDataSet: new DataSet({
      events: {
        update({ record, name /* value */ }) {
          if (name === 'siteLov') {
            record.set('materialIdLov', null);
            record.set('supplierLov', null);
          }
        },
      },
      fields: [
        {
          name: 'siteLov',
          type: FieldType.object,
          lovCode: 'MT.APS.PURCHASE.SITE.PERMISSION',
          ignore: FieldIgnore.always,
          label: intl.get(`${modelPrompt}.form.site`).d('采购站点'),
          lovPara: {
            tenantId,
            userId,
          },
        },
//查询时，选取siteId作为value,purchaseSiteId作为key
        {
          name: 'purchaseSiteId', //这个是查询入参字段
          bind: 'siteLov.siteId', //这个是lov接口返回的取值字段
        },
  
        {
          name: 'materialIdLov',
          type: FieldType.object,
          ignore: FieldIgnore.always,
          label: intl.get(`${modelPrompt}.form.materialCode`).d('物料编码'),
          lovCode: 'MT.APS.MATERIAL.SITE',
          multiple: true,
          dynamicProps: {
            lovPara({ record }) {
              return {
                tenantId,
                userId,
                purchaseId: record.get('siteId'), 
              };
            },
          },
        },
        {
          name: 'materialIds',
          bind: 'materialIdLov.materialId',
        },
        // {
        //   name: 'materialCodes',
        //   bind: 'materialIdLov.materialCode',
        // },
        {
          name: 'supplierLov',
          type: FieldType.object,
          label: intl.get(`${modelPrompt}.form.supplierCode`).d('供应商编码'),
          ignore: FieldIgnore.always,
          lovCode: 'HPS.PURCHASE.SUPPLIER',
          multiple: true,
          dynamicProps: {
            lovPara({ record }) {
              return {
                tenantId,
                userId,
                purchaseId: record.get('siteId'), // 采购站点id
              };
            },
          },
        },
        {
          name: 'supplierIds',
          bind: 'supplierLov.supplierId',
        },
        // {
        //   name: 'supplierCode',
        //   bind: 'supplierLov.supplierCode',
        // },
    
        {
          name: 'mrpController',
          type: FieldType.string,
          label: intl.get(`${modelPrompt}.form.mrpController`).d('MRP控制者'),
        },
      ],
    }),
    events: {
      update({ record, name, value }) {
        // 采购站点发生改变时,物料编码/供应商编码清空
        if (name === 'siteLov') {
          console.log('value',value);
          
          record.set('materialLov', null);
          record.set('supplierLov', null);
        }
        if (record.get('siteLov') && record.get('materialLov')){
          const url = ''
          // fetchUnitQty(url).then(res => {
          //   if (res) {
          //     const { success, message, rows } = res;
          //     if (success && rows) {
          //       record.set('unitQty', rows);
          //       record.setState('autoUnitQty', true);
          //     } else if (message) {
          //       notification.warning({ message });
          //     }
          //   }
          // })
        }
      },
    },
    fields: [
      {
        name: 'siteLov',
        type: FieldType.object,
        label: intl.get(`${modelPrompt}.table.site`).d('采购站点'),
        required: true,
        lovCode: 'MT.APS.PURCHASE.SITE.PERMISSION',
        lovPara: {
          tenantId,
          userId,
        },
        ignore: FieldIgnore.always,
      },
      {
        name: 'siteId',
        bind: 'siteLov.siteId',
      },
      {
        name: 'purchaseSiteCode', //后端返回字段
        bind: 'siteLov.siteCode', //lov返回字段
      },
      {
        name: 'materialLov',
        type: FieldType.object,
        label: intl.get(`${modelPrompt}.table.materialCode`).d('物料编码'),
        required: true,
        ignore: FieldIgnore.always,
        lovCode: 'MT.APS.MATERIAL.SITE',
        dynamicProps: {
          lovPara({ record }) {
            return {
              tenantId,
              userId,
              purchaseId: record.get('siteId'), // 采购站点id
            };
          },
        },
      },
      {
        name: 'materialId',
        bind: 'materialLov.materialId',
      },
      {
        name: 'materialCode',
        bind: 'materialLov.materialCode',
      },
      {
        name: 'materialName',
        type: FieldType.string,
        label: intl.get(`${modelPrompt}.table.materialName`).d('物料描述'),
        dynamicProps: {
          bind({ record }) {
            if (record.get('materialLov') && record.get('materialLov').materialId) {
              return 'materialLov.materialName';
            } else {
              return undefined;
            }
          },
        },
      },
      {
        name: 'supplierLov',
        type: FieldType.object,
        label: intl.get(`${modelPrompt}.table.supplier`).d('供应商编码'),
        lovCode: 'HPS.PURCHASE.SUPPLIER',
        dynamicProps: {
          lovPara({ record }) {
            return {
              tenantId,
              userId,
              purchaseId: record.get('siteId'), // 采购站点id
            };
          },
        },
        ignore: FieldIgnore.always,
      },
      {
        name: 'supplierId',
        bind: 'supplierLov.supplierId',
      },
      {
        name: 'supplierName',
        type: FieldType.string,
        label: intl.get(`${modelPrompt}.table.supplierName`).d('供应商名称'),
        dynamicProps: {
          bind({ record }) {
            if (record.get('supplierLov') && record.get('supplierLov').supplierName) {
              return 'supplierLov.supplierName';
            } else {
              return undefined;
            }
          },
        },
      },

      {
        name: 'procurementGroup',
        label: intl.get(`${modelPrompt}.table.procurementGroup`).d('采购组'),
        type: FieldType.string,
      },
      {
        name: 'mrpController',
        type: FieldType.string,
        label: intl.get(`${modelPrompt}.table.mrpController`).d('MRP控制者'),
      },
   
    ],
    transport: {
      read: (config: AxiosRequestConfig): AxiosRequestConfig => {
        return {
          ...config,
          url: `${API_HOST}/aps/v1/${getCurrentOrganizationId()}/hps-env-material-lists/list/ui`,
          transformResponse: (value) => {
            let listData: any = {};
            try {
              listData = JSON.parse(value);
              console.log('listData', listData);
            } catch (err) {
              listData = {
                message: err,
              };
            }
            if (!listData) {
              return {
                ...listData,
                failed: true,
              };
            } else {
              return listData;
            }
          },
        };
      },
    },
  });

export default listPageFactory;
